//
//  ViolationViewController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/4/20.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import UIKit
import SwiftyJSON
import Alamofire
//违章
class ViolationViewController: UIViewController {
    var violationArray: [OrderModel]!
    var violationTable:UITableView!//数据表格
    var dataUrl = "listdata"
    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化表格
        violationTable = UITableView(frame: CGRect(x:0,y:kStatusBarH + kNavigationBarH + 40,width:kScreenW,height:kScreenH),style: UITableViewStyle.plain)
        violationTable?.delegate = self
        violationTable?.dataSource = self
        violationTable?.backgroundColor = tableBgColor
        violationTable?.separatorStyle = UITableViewCellSeparatorStyle.none
        violationTable?.rowHeight = 123
        self.view.addSubview(violationTable!)
        violationTable?.snp.makeConstraints({ (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(kStatusBarH + kNavigationBarH + 40)//选项卡高度 40
            make.bottom.equalTo(self.view).offset(-kTabBarH)
        })
    }
    override func viewWillAppear(_ animated: Bool) {
        violationArray = Array<OrderModel>()
        super.viewWillAppear(animated)
        if("2" == isEmployee){
            if("1" == pageTag){
               dataUrl = "todolist"
            }else if ("2" == pageTag){
               dataUrl = "mydolist"
            }
        }
        if  reachability.isReachable{
            createData()
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
extension ViolationViewController{
    func createData() {
        let urlString = "\(projectUrl)/order/car/\(dataUrl)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
        Alamofire.request(urlString, method: .get, parameters: [:], headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    for (_,orderJson) : (String,JSON) in json["rdata"] {
                        let model = OrderModel.init(dict: orderJson)
                        self.violationArray.append(model)
                    }
                    self.violationTable.reloadData()
                }
                else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
    //登录失效 清除缓存
    func failOperNoticeFun(code:String,message:String){
        let alertController = UIAlertController(title: "通知", message: message, preferredStyle: .alert)
        if("000" == code){
            let okAction = UIAlertAction(title: "去登录", style: .default, handler:{
                (UIAlertAction) -> Void in
                if(PersonalModel.deletePersonal(userID: userID! as! String)){
                    let userDefault = UserDefaults.standard
                    userDefault.removeObject(forKey: "userID")
                    userDefault.removeObject(forKey: "tokenID")
                    userDefault.removeObject(forKey: "isEmployee")
                    let mainVC = UINavigationController(rootViewController: LoginController())
                    app.window?.rootViewController = mainVC
                }
            })
            alertController.addAction(okAction)
        }else{
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
        }
        self.present(alertController, animated: true, completion: nil)
    }
}
extension ViolationViewController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return violationArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell: ViolationTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "orderCellID") as? ViolationTableViewCell
        if cell == nil {
            cell = ViolationTableViewCell(style: UITableViewCellStyle.default,reuseIdentifier: "orderCellID")
        }
        if violationArray.count > 0 {
            let model = violationArray[(indexPath as NSIndexPath).row]
            cell?.configCellDateWithModel(model)
        }
        cell?.selectionStyle = UITableViewCellSelectionStyle.default
        return cell!
    }
    //选中cell时触发这个代理
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: false)//点击完成，取消高亮
        let vsc = ViolationSubmitController()
        let model = violationArray[(indexPath as NSIndexPath).row]
        vsc.orderID = model.orderNo
        self.present(vsc, animated: true, completion: nil)
    }
}
